using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;

namespace UniversalAdmin.WebApi.Controllers;

[ApiController]
[Route("api/v1/[controller]")]
public class RagController : ControllerBase
{
    private readonly IRagService _ragService;

    public RagController(IRagService ragService)
    {
        _ragService = ragService;
    }

    [HttpPost("query")]
    [Authorize]
    public async Task<IActionResult> ProcessQuery([FromBody] RagQueryDto dto)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        if (string.IsNullOrEmpty(dto.Query))
        {
            return BadRequest(new { message = "查询内容不能为空" });
        }

        if (string.IsNullOrEmpty(dto.SessionId))
        {
            // 如果没有提供会话ID，生成一个新的
            dto.SessionId = Guid.NewGuid().ToString();
        }

        try
        {
            var result = await _ragService.ProcessQueryAsync(Guid.Parse(userId), dto.Query, dto.SessionId);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "处理查询时发生错误", details = ex.Message });
        }
    }

    [HttpGet("related-documents")]
    [Authorize]
    public async Task<IActionResult> GetRelatedDocuments([FromQuery] string query, [FromQuery] int topK = 5)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        if (string.IsNullOrEmpty(query))
        {
            return BadRequest(new { message = "查询内容不能为空" });
        }

        try
        {
            var documents = await _ragService.GetRelatedDocumentsAsync(Guid.Parse(userId), query, topK);
            return Ok(documents);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取相关文档时发生错误", details = ex.Message });
        }
    }

    [HttpGet("session-context/{sessionId}")]
    [Authorize]
    public async Task<IActionResult> GetSessionContext(string sessionId, [FromQuery] int maxTokens = 1000)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        try
        {
            // 检查会话是否属于当前用户
            var chatHistories = await _ragService.GetSessionContextAsync(sessionId);
            if (string.IsNullOrEmpty(chatHistories))
            {
                return Ok(new { context = string.Empty });
            }

            return Ok(new { context = chatHistories });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取会话上下文时发生错误", details = ex.Message });
        }
    }
}

// RAG查询DTO
public class RagQueryDto
{
    public string Query { get; set; }
    public string SessionId { get; set; }
}